package cn._51doit.day09;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.List;

/**
 * @create: 2021-10-26 19:42
 * @author: 今晚打脑斧先森
 * @program: ProcessingTimeTimer
 * @Description:
 *   只有KeyedStream，使用KeyedProcessFunction才可以使用定时器
 *
 *   使用ProcessingTime注册定时器
 **/
public class ProcessingTimeTimer {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> lines = env.socketTextStream("doit01", 8888);
        SingleOutputStreamOperator<Tuple2<String, Integer>> mapped = lines.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                String[] split = value.split(",");
                return Tuple2.of(split[0], Integer.parseInt(split[1]));
            }
        });
        //先keyby在使用定时器
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = mapped.keyBy(t -> t.f0);
        SingleOutputStreamOperator<Tuple2<String, Integer>> res = keyedStream.process(new KeyedProcessFunction<String, Tuple2<String, Integer>, Tuple2<String, Integer>>() {
            private transient ValueState<List<Tuple2<String, Integer>>> listValueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                //使用全量聚合
                ValueStateDescriptor<List<Tuple2<String, Integer>>> descriptor = new ValueStateDescriptor<>("全量聚合", TypeInformation.of(new TypeHint<List<Tuple2<String, Integer>>>() {
                }));
                listValueState = getRuntimeContext().getState(descriptor);
            }

            @Override
            public void processElement(Tuple2<String, Integer> value, Context ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
                //在processElement中不输出数据,而是攒起来,然后注册定时器
                //攒起来的数据放到状态中,还可以容错
                List<Tuple2<String, Integer>> list = listValueState.value();
                if (list == null) {
                    list = new ArrayList<>();
                }
                list.add(value);
                listValueState.update(list);

                //注册定时器
//                ctx.timerService().registerProcessingTimeTimer(System.currentTimeMillis() + 15000); //15秒钟只会会触发onTimer方法
                //为了演示清除中间都做了什么,采用下面的注册定时器的方式
                //11:29:15 下一次触发的时间11：30：00
                //11:29:18 下一次触发的时间11：30：00
                long triggerTime = (System.currentTimeMillis() - System.currentTimeMillis() % 60000) + 60000;   //当前时间-当前时间不能被60000整除的时间+60000,就是一分钟触发一次,不管你现在是这一分钟的第几秒,都会在下一分钟前触发一次定时器
                System.out.println(ctx.getCurrentKey() + "注册定时器的时间：" +  System.currentTimeMillis() + ", 定时器触发的时间：" + triggerTime);

                //相同key,如果注册了多个触发时间相同的定时器，只会触发一次（后面注册的定时器会覆盖前面的定时器）
                ctx.timerService().registerProcessingTimeTimer(triggerTime);

            }

            //定时器触发后会调用onTimer方法（每个key都有单独的定时器，每个key的定时器触发了都会调用一个onTimer方法）
            @Override
            public void onTimer(long timestamp, OnTimerContext ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
                System.out.println("触发定时器的时间为: " + timestamp);
                List<Tuple2<String, Integer>> list = listValueState.value();
                for (Tuple2<String, Integer> tp : list) {
                    out.collect(tp);
                }
                list.clear();
            }
        });
        res.print();
        env.execute();
    }
}
